class VolcanoTTSClient {
    constructor() {
        this.url = "https://openspeech.bytedance.com/api/v1/tts";
        this.authHeader = "Bearer;j4fK6AOAP0o1NPTwE9giP8uX7X2GpCSP";
        this.appid = "7710274461";
        this.token = "j4fK6AOAP0o1NPTwE9giP8uX7X2GpCSP";
        this.voiceType = "BV700_streaming";
        this.onAudioClipReceived = new Event("audioClipReceived");
    }

    requestTTS(text) {
        this.sendTTSRequest(text).then(audioClip => {
            if (audioClip) {
                document.dispatchEvent(new CustomEvent("audioClipReceived", { detail: audioClip }));
            }
        }).catch(error => {
            console.error(`Error: ${error}`);
        });
    }

    async sendTTSRequest(text) {
        const requestBody = {
            app: {
                appid: this.appid,
                token: this.token,
                cluster: "volcano_tts"
            },
            user: {
                uid: "uid123"
            },
            audio: {
                voice_type: this.voiceType,
                encoding: "wav",
                compression_rate: 1,
                rate: 24000,
                speed_ratio: 1.0,
                volume_ratio: 1.0,
                pitch_ratio: 1.0,
                emotion: "happy",
                language: "cn"
            },
            request: {
                reqid: "uuid",
                text: text,
                text_type: "plain",
                operation: "query",
                silence_duration: "125",
                with_frontend: "1",
                frontend_type: "unitTson",
                pure_english_opt: "1"
            }
        };

        const jsonData = JSON.stringify(requestBody);
        const response = await fetch(this.url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": this.authHeader
            },
            body: jsonData
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const responseText = await response.text();
        return this.processTTSResponse(responseText);
    }

    processTTSResponse(response) {
        try {
            // console.log("response: " + response[:10]);
            const jsonResponse = JSON.parse(response);

            if (jsonResponse && jsonResponse.data) {
                const audioBytes = atob(jsonResponse.data);
                const audioArray = new Uint8Array(audioBytes.length);
                for (let i = 0; i < audioBytes.length; i++) {
                    audioArray[i] = audioBytes.charCodeAt(i);
                }

                const audioBlob = new Blob([audioArray], { type: "audio/wav" });
                const audioUrl = URL.createObjectURL(audioBlob);
                const audio = new Audio(audioUrl);
                return audio;
            } else {
                console.error("No data field in response.");
            }
        } catch (e) {
            console.error(`Error processing TTS response: ${e.message}`);
        }
        return null;
    }

    
}

// Example usage